<%
  config = field.associated_model_config
  source_abstract_model = RailsAdmin.config(form.object.class).abstract_model

  selected = form.object.send(field.name)
  selected_ids = selected.map{|s| s.send(field.associated_primary_key).to_s}

  current_action = params[:action].in?(['create', 'new']) ? 'create' : 'update'

  xhr = !field.associated_collection_cache_all

  collection = if xhr
    selected.map { |o| [o.send(field.associated_object_label_method), o.send(field.associated_primary_key)] }
  else
    i = 0
    controller.list_entries(config, :index, field.associated_collection_scope, false).map { |o| [o.send(field.associated_object_label_method), o.send(field.associated_primary_key).to_s] }.sort_by {|a| [selected_ids.index(a[1]) || selected_ids.size, i+=1] }
  end

  js_data = {
    xhr: xhr,
    :'edit-url' => (field.inline_edit && authorized?(:edit, config.abstract_model) ? edit_path(model_name: config.abstract_model.to_param, id: '__ID__') : ''),
    remote_source: index_path(config.abstract_model, source_object_id: form.object.id, source_abstract_model: source_abstract_model.to_param, associated_collection: field.name, current_action: current_action, compact: true),
    scopeBy: field.dynamic_scope_relationships,
    sortable: !!field.orderable,
    removable: !!field.removable,
    cacheAll: !!field.associated_collection_cache_all,
    regional: {
      add: t('admin.misc.add_new'),
      chooseAll: t('admin.misc.chose_all'),
      clearAll: t('admin.misc.clear_all'),
      down: t('admin.misc.down'),
      remove: t('admin.misc.remove'),
      search: t('admin.misc.search'),
      up: t('admin.misc.up')
    }
  }
%>
<div class="row">
  <div class="col-auto">
    <input name="<%= form.dom_name(field) %>" type="hidden" />
    <% selected_ids = (hdv = field.form_default_value).nil? ? selected_ids : hdv %>
    <%= form.select field.method_name, collection, { selected: selected_ids, object: form.object }, field.html_attributes.reverse_merge({data: { filteringmultiselect: true, options: js_data.to_json }, multiple: true}) %>
  </div>
  <% if authorized?(:new, config.abstract_model) && field.inline_add %>
    <div class="col-sm-4 modal-actions">
      <% path_hash = { model_name: config.abstract_model.to_param, modal: true }.merge!(field.associated_prepopulate_params) %>
      <%= link_to "<i class=\"fas fa-plus\"></i> ".html_safe + wording_for(:link, :new, config.abstract_model), '#', data: { link: new_path(path_hash) }, class: "create btn btn-info", style: 'margin-left:10px' %>
    </div>
  <% end %>
</div>